<template>
  <div>
    <div class="i-layout-page-header mb20">
      <div class="i-layout-page-header">
        <span class="ivu-page-header-title">{{ $route.meta.title }}</span>
      </div>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form
        ref="roleData"
        :model="roleData"
        :label-width="labelWidth"
        :label-position="labelPosition"
        @submit.native.prevent
      >
	    <Row type="flex" :gutter="24">
	      <Col v-bind="grid">
	        <FormItem label="关键字：" label-for="keywords">
	          <Input
	            search
	            enter-button
	            placeholder="请输入关键字"
	            v-model="formValidate.keywords"
	            @on-search="userSearchs"
	          />
	        </FormItem>
	      </Col>
	    </Row>
        <Row type="flex">
          <Col v-bind="grid">
            <Button type="primary" @click="menusAdd('销售开单')" icon="md-add">销售开单</Button
            >
          </Col>
        </Row>
      </Form>
      <Table
        :columns="columns"
        :data="tableData"
        ref="table"
        :loading="loading"
        highlight-row
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
        @on-select="handleSelectRow"
        @on-select-cancel="handleCancelRow"
        @on-select-all="handleSelectAll"
        @on-select-all-cancel="handleSelectAll"
        class="orderData mt25"
      >
	    <template slot-scope="{ row, index }" slot="id">
	      {{index+1}}
	    </template>
        <template slot-scope="{ row, index }" slot="no">
          <span>{{row.no}}号</span>
        </template>
		<template slot-scope="{ row, index }" slot="status">
			<span v-if="row.status == 0">待支付</span>
			<span v-else-if="row.status == 1">已支付</span>
			<span v-else>已完成</span>
		</template>
        <template slot-scope="{ row, index }" slot="action">
			<template v-if="row.status == 0">
				<a @click="pay(row)">支付</a>
				<Divider type="vertical"/>
				<a @click="edit(row)">编辑</a>
			</template>
            <template v-else-if="row.status == 1">
				<a @click="edit(row)">编辑</a>
				<Divider type="vertical"/>
				<a @click="print(row)">打印</a>
				<Divider type="vertical"/>
				<a @click="finished(row)">已完成</a>
		    </template>
            <template v-else>
				<a @click="print(row)">打印</a>
		    </template>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page
          :total="page.total"
          :current="page.pageNum"
          show-elevator
          show-total
          @on-change="pageChange"
          :page-size="page.pageSize"
          @on-page-size-change="limitChange"
        />
      </div>
    </Card>
    <menus-form
      :formValidate="formValidate"
      :titleFrom="titleFrom"
      @getList="getList"
	  @showArchiveModal="showArchiveModal"
      @selectRule="selectRule"
      ref="menusForm"
      @clearFrom="clearFrom"
	  @receiveModalData="receiveModalData"
    ></menus-form>
    <archive-form
      :formValidate="formValidate2"
      :titleFrom="archiveFrom"
      ref="archiveForm"
	  @receiveData="receiveData"
    ></archive-form>
    <sale-result
      :formValidate="formValidate2"
      titleFrom="销售单"
      ref="saleResult"
    ></sale-result>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { ListApi } from '@/api/usersale';
import formCreate from '@form-create/iview';
import menusForm from './components/menusForm'; 
import archiveForm from './components/archiveForm'; 
import saleResult from './components/saleResult'; 
export default {
  name: 'systemMenus',
  data() {
    return {
      tabconfig: { children: 'children', reserve: true, accordion: true },
      spinShow: false,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      roleData: {
        is_show: '',
        keyword: '',
      },
      loading: false,
      tableData: [],
      FromData: null,
      icons: '',
      formValidate: {
		  
	  },
      formValidate2: {
		  
	  },
      titleFrom: '',
      modalTitleSs: '',
	  archiveFrom:'',
	  columns: [
		{
	      title: '序号',
	      align: 'center',
	      slot: 'id',
	      width: 80,
	    },
		{
	      title: '制单时间',
	      align: 'center',
	      key: 'created_time',
	      minWidth: 130,
	    },
		{
	      title: '销售单号',
	      align: 'center',
	      key: 'no',
	      minWidth: 130,
	    },
		{
	      title: '客户信息',
	      align: 'center',
	      key: 'user_name',
	      minWidth: 100,
	    },
		{
	      title: '手机号码',
	      align: 'center',
	      key: 'user_phone',
	      minWidth: 100,
	    },
		{
	      title: '订单金额（元）',
	      align: 'center',
	      key: 'total',
	      minWidth: 150,
	    },
		{
	      title: '销售员',
	      align: 'center',
	      key: 'saler_name',
	      minWidth: 100,
	    },
		{
	      title: '订单状态',
	      align: 'center',
	      slot: 'status',
	      minWidth: 100,
	    },
	    {
	      title: '操作',
	      slot: 'action',
	      fixed: 'right',
	      width: 150,
	      align: 'center',
	    },
	  ],
	  page: {
	    total: 0, // 总条数
	    pageNum: 1, // 当前页
	    pageSize: 10, // 每页显示条数
	  },
	  keywords:'',
	  items:[]
    };
  },
  components: { menusForm,archiveForm,saleResult, formCreate: formCreate.$form() },
  computed: {
    ...mapState('admin/layout', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : 75;
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'right';
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    // 查看详情
    detail(row) {
		console.info(111)
	  this.$router.push({ path: '/admin/contract/detail/' + row.id });
    },
    // 请求列表
    getList() {
      this.formValidate = Object.assign({}, this.$options.data().formValidate);
      this.getData();
    },
    selectRule(data) {
      this.formValidate.menu_name = data.real_name;
      this.formValidate.methods = data.method;
      this.formValidate.api_url = data.rule;
    },
    // 清除表单数据
    clearFrom() {
      this.formValidate = Object.assign({}, this.$options.data().formValidate);
	  this.items = [];
    },
    // 删除
    del(row) {
      let delfromData = {
        title: '删除数据',
        url: `/subscribe/del/${row.id}`,
        method: 'GET',
        ids: '',
      };
      this.$modalSure(delfromData)
        .then((res) => {
          this.$Message.success(res.msg);
          this.getData();
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 获取详情
    getDetails(id) {
		
    },
    // 添加
    menusAdd(title) {
	  this.items = [];
      this.formValidate = {};
      this.$refs.menusForm.modals = true;
      this.$refs.menusForm.valids = false;
      // this.formValidate = Object.assign(this.$data, this.$options.formValidate());
      this.titleFrom = title;
	  this.$refs.menusForm.resetData(this.items);
    },
    // 添加
    print(row) {
      this.formValidate2 = {};
      this.$refs.saleResult.modals = true;
	  this.formValidate2 = row;
	  console.info(row)
    },
	
	// 编辑
	edit(row) {
	  this.formValidate = {
		  id:row.id,
		  uid:row.uid,
		  sale_id:row.sale_id
	  };
	  this.$refs.menusForm.modals = true;
	  this.$refs.menusForm.valids = false;
	  this.titleFrom = '编辑';
	  if(row.items){
		  let arr = [];
		  row.items.forEach(function(item){
			  arr.push({
				  id:item.p_id,
				  num:item.num,
				  old_price:item.source_price,
				  price:item.price,
				  remark:item.remark,
				  name:item['product'].name
			  });
		  })
		  this.items = arr;
		  console.info(this.items);
	  }else{
		  this.items = [];
		  console.info(1231)
	  }
	  this.$refs.menusForm.resetData(this.items);
	},
    getData() {
		// this.page.pageNum = res === 1 ? 1 : this.page.pageNum;
		this.loading = true;
		ListApi({
		  page: this.page.pageNum,
		  limit: this.page.pageSize,
		  keywords:this.keywords
		})
		  .then(async (res) => {
		    let data = res.data;
		    this.tableData = data.list;
		    this.page.total = data.count;
		    this.loading = false;
		  })
		  .catch((res) => {
		    this.loading = false;
		    this.$Message.error(res.msg);
		  });
    },
	pageChange(index) {
	  this.page.pageNum = index;
	  this.getData();
	},
	limitChange(limit) {
	  this.page.pageSize = limit;
	  this.getData();
	},
    // 关闭按钮
    cancel() {
      this.$emit('onCancel');
    },
	//  选中某一行
	handleSelectRow(selection, row) {
	  this.isDel(selection);
	  this.selectedIds.add(row.id);
	  this.$nextTick(() => {
	    //确保dom加载完毕
	    this.setChecked();
	  });
	},
	//  取消某一行
	handleCancelRow(selection, row) {
	  this.isDel(selection);
	  this.selectedIds.delete(row.id);
	  this.$nextTick(() => {
	    //确保dom加载完毕
	    this.setChecked();
	  });
	},
	//全选和取消全选时触发
	handleSelectAll(selection) {
	  if (selection.length === 0) {
	    //获取table的数据；
	    let data = this.$refs.table.data;
	    data.forEach((item) => {
	      if (this.selectedIds.has(item.id)) {
	        this.selectedIds.delete(item.id);
	      }
	    });
	  } else {
	    selection.forEach((item) => {
	      this.selectedIds.add(item.id);
	    });
	  }
	  this.isDel(selection);
	  this.$nextTick(() => {
	    //确保dom加载完毕
	    this.setChecked();
	  });
	},
	userSearchs(){
		this.keywords = this.formValidate.keywords;
		this.page.pageNum = 1;
		this.getData();
		console.info(this.formValidate)
	},
	//弹出建档
	showArchiveModal(){
		console.info(22)
		this.formValidate2 = {};
		this.$refs.archiveForm.modals = true;
		this.$refs.archiveForm.valids = false;
		this.archiveFrom = "选择项目";
	},
	//支付费用
	pay(row){
		this.delfromData = {
		  title: '收费确认',
		  info: '确认已收取费用吗?',
		  url: `/usersale/pay_offline/${row.id}`,
		  method: 'get',
		  ids: '',
		};
		this.$modalSure(this.delfromData)
		  .then((res) => {
		    this.$Message.success(res.msg);
		    this.getList();
		  })
		  .catch((res) => {
		    this.$Message.error(res.msg);
		  });
	},
	//完成
	finished(row){
		let delfromData = {
		  title: '完成确认',
		  info: '确认已完成吗?',
		  url: `/usersale/finished/${row.id}`,
		  method: 'GET',
		  ids: '',
		};
		this.$modalSure(delfromData)
		  .then((res) => {
		    this.$Message.success(res.msg);
		    this.getData();
		  })
		  .catch((res) => {
		    this.$Message.error(res.msg);
		  });
	},
	receiveModalData(datas) {
		console.info(444)
		this.items = datas;
	},
	//接收选择的项目
	receiveData(row) {
		let that = this;
		let flag = false;
		this.items.forEach(function(n){
			if(n.id == row.id){
				flag = true;
				return;
			}
		});
		if(flag){
			that.$Message.error("【"+row.name+"】"+"已存在");
			return;
		}
		this.items.push(Object.assign({}, row));
        this.$refs.menusForm.resetData(this.items);
		
		this.$Message.success('添加成功');
	},
  },
};
</script>

<style scoped lang="stylus">
.vxeTable {
  >>> .vxe-table--header-wrapper {
    background: #fff !important;
  }
}
</style>
